/** email function */
function createURLForCurve(x,obj,widgetName){
	var plot=jQueryEnterprise("img."+widgetName);
    obj=eval('('+obj+')');
    var stamp = "car."+new Date().getTime().toString(36);
    var height=350;
    var width=470;
    var isThumbnail = obj['isThumbnail'];
    if(isThumbnail) { height=100; width=100;}
    var model=JSON.stringify(obj['model']);
   	var data = { model: model, format: "PNG", w: width, h: height };
   
       // first send the big data to the server and refer to it in the image URL
        CSC.rest("cache", data, function(text) {
            text = eval('('+text+')');
            var token = text.token;
            plot.attr('src', CSC.getContextPath()+"/servlet/rest/plot?cache="+token+"&rand="+stamp);
        },function(error){
        	error = function(xhr, status, e) {
                switch(xhr.status) {
                    case 401:
                    case 0:	
                    default:
                        alert("error ("+cmd+"): "+xhr.status+": "+e);
                        break;
                }
            };
        });
        
        if(plot.parent("a").length) {
            var winHt = $(window).height();
            var winwt = $(window).width();
            var hfht=winHt-130;
            var winwt1=((winwt-100) * (0.75));
            winwt1 = Math.round(winwt1);
           var md= obj['model'];
           md['axes']['x']['visible']=true;
           md['axes']['y']['visible']=true;
           md['showGrid']=true;
           md['showLegend']=true;
           model=JSON.stringify(md);
            var m = encodeURIComponent(model);
        	var anchr=plot.parent();
        	anchr.click(function(event,md){
        		  var	dialog = jQueryEnterprise("<div class='filterDiv1'><table style='margin: 0px auto 0px auto;'></table></div>");
          	    var d = dialog.dialog({ title: "Filter",
          	        width: "800", height: 'auto', modal: true, maxHeight: 800, maxHeight: 800
          	    });
          	    var ok = "OK"; 
          	    var cancel = "Cancel"; 
          	    d.dialog("option", "buttons", [
          	        { text: cancel, click: function() {jQueryEnterprise(d).dialog('close');} }
          	    ]);
          	    dialog.car(md.sources, md.args);
        	 });	
          
        }
}

function openMultipleCurveLink(anchr,jsonObj){
	var rpc = CSC.newRpcClient();
	var json = rpc.mod.createCurveURLJSON(JSON.stringify(jsonObj)); 
	var id = $(anchr).attr("id");
	var md=eval('('+json+')');
    var winHt = $(window).height();
    var winwt = $(window).width();
    var hfht=winHt-130;
    var winwt1=((winwt-100) * (0.75));
    var dialogTitle=md['dialogTitle'];
    winwt1 = Math.round(winwt1);
   md['showGrid']=true;
   md['showLegend']=true;
   model=JSON.stringify(md);
    var m = encodeURIComponent(model);
		  var	dialog = jQueryEnterprise("<div class='filterDiv1'><table style='margin: 0px auto 0px auto;'></table></div>");
		  var d = dialog.dialog({ title: dialogTitle,
	  	        width: winwt1, height: hfht, modal: true, maxHeight: winwt, maxHeight: winHt
	  	    });
  	    var ok = "OK"; 
  	    var cancel = "Cancel"; 
  	    d.dialog("option", "buttons", [
  	        { text: cancel, click: function() {jQueryEnterprise(d).dialog('close');} }
  	    ]);
  	    dialog.car(md.sources, md.args);
}

function openCurve(anchr,jsonObj){	
	var rpc = CSC.newRpcClient();
	var json = rpc.mod.createCARJSON(JSON.stringify(jsonObj));   
	json=eval('('+json+')');
	openCurveDialog(anchr,json);
}

function openCurveDialog(anchr, json) {
	var anchr = jQueryEnterprise(anchr);
	var winHt = $(window).height();
	var winwt = $(window).width();
	var hfht = winHt - 130;
	var winwt1 = ((winwt - 100) * (0.75));
	var dialogTitle = json['dialogTitle'];
	winwt1 = Math.round(winwt1);
	var dialog = jQueryEnterprise("<div class='filterDiv1'><table style='margin: 0px auto 0px auto;'></table></div>");
	APP.hideBusy();
	setTimeout(function() {

		var d = dialog.dialog({
			title : dialogTitle,
			width : winwt1,
			height : hfht,
			modal : true,
			maxHeight : winwt,
			maxHeight : winHt,
			dialogClass: 'filterDialog'
		});
		var ok = "OK";
		var cancel = "Cancel";
		d.dialog("option", "buttons", [ {
			text : cancel,
			click : function() {
				jQueryEnterprise(d).dialog('close');
			}
		} ]);
		dialog.car(json.curves, json.args);

	}, 1);
}



/** email function */
function email(subject,url){
	 var link = "mailto:"
         + "?subject=" + subject
         + "&body=" + url;
	 window.open(link, '_blank');
}


/** this function is to  Validation for "only space entry" in text field */
function smIsEmpty( element ) {
var ele=jQueryEnterprise(element);
  var textVal = ele.val();
  var trimmed = textVal.replace( /^\s+|\s+$/g, '' );
  if ( trimmed.length == 0 ) {
	  ele.val("");
  }
}

/** Returns the an JSON RCP client instance for RPC calls. */
function getRPCClient() {
	return CSC.newRpcClient();
};

var autoTimeOut;

function sodRefreshtimer(qry,fun,stat,time,childCount,messageCount) {
	var status = '';
	var rpc = getRPCClient();
	var isRefreshNeeded = rpc.process.getProcessQueueStatus(qry,stat,messageCount,childCount);
	if (isRefreshNeeded == true) {
		eval(fun)();
		return;
	}
	var func="sodRefreshtimer('"+qry+"','"+fun+"','"+stat+"','"+time+"','"+childCount+"','"+messageCount+"')";
	autoTimeOut = setTimeout(func, time);
};

function checkProcessStatus(qry, status, fun,time,childCount,messageCount) {
	var func="sodRefreshtimer('"+qry+"','"+fun+"','"+status+"','"+time+"','"+childCount+"','"+messageCount+"')";
	autoTimeOut = setTimeout(func, time);
};

function stopAutoTimer(){
	window.clearTimeout(autoTimeOut);
};
/**
 * Clear all other radio buttons in the same column of the <table> element generated by JSF
 * h:dataTable when the given radio button is clicked.
 * @param radio The <input type="radio"> element which was clicked.
 */
function dataTableSelectOneRadio( radio ) {
  var id = radio.name.substring( radio.name.lastIndexOf( ':' ) );
  var elements = radio.form.elements;
  for ( var i = 0; i < elements.length; i++ ) {
    if ( elements[i].name.substring( elements[i].name.lastIndexOf( ':' ) ) == id ) {
      elements[i].checked = false;
    }
  }
  radio.checked = true;
}

/** Escapes all URL specific characters. */
function e( str ) {
  return encodeURIComponent( str );
}

/** This function puts the page in the top most frame. */
function smEnsureTop( ) {
  if ( self != top ) 
    top.location.href = self.location.href;
}

/**
 * Shows the uploader applet
 * @param json is serialized string of selected client files
 * @param ctx is context path
 */
function enableApplet( json, ctx, pid, key, logLevels, fileSelectionType ) {
	  var protocol = location.protocol + "//" + location.host;
	  var url = protocol + ctx;
	  json = json.replace( /\\/g, "\\\\" );
	  var strs = document.cookie.split( ";" ); 
	  var jses = "";
	  for ( var i = 0; i < strs.length; i++ ) {
	    if ( strs[i].indexOf( "JSESSIONID" ) != -1 )
	      jses = strs[i].substring( strs[i].indexOf( "=" ) + 1, strs[i].length );
	  }
	  	  
	  var randomnumber = Math.floor( Math.random( ) * 11 );	
	  upload = window.open( "", "uploader" + randomnumber, "toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width=480,height=550" );	  
	  upload.document.write( '<HTML> <HEAD> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> </HEAD>' );
	  upload.document.write( '<BODY bgcolor="#F0F0F0">' );
	  upload.document.write( '<B> <FONT COLOR="RED">Close this window only after the \"Close\" Button is enabled!</FONT></B>' );
	  upload.document.write( '<BR>' );
	  if(fileSelectionType == 'mfs'){
		  upload.document.write( "<APPLET CODE='com.msc.sdm.ui.widget.toolkit.sm.applet.efs.mfs.ClientFileUploader' " );
	  } else {		  
		  upload.document.write( "<APPLET CODE='com.msc.sdm.ui.widget.toolkit.sm.applet.efs.view.EfsUploader' " );
	  }
	  upload.document.write( "<APPLET ID='efsUploader' " );
	  upload.document.write( "ARCHIVE='efs.jar, json.jar, rhino.jar' " );
	  upload.document.write( "CODEBASE=" + ctx + "/java/efs " );
	  upload.document.write( "WIDTH=460 " );
	  upload.document.write( "HEIGHT=480>" );

      var jsonArr  = json.match(/.{1,2048}/g);
      var jsonSegs = jsonArr.length;
	  upload.document.write( "<PARAM NAME='JSON_SEGS' VALUE='" + jsonSegs + "'>" );
	  for (var n=0; n < jsonSegs; n++) {
	  	upload.document.write( "<PARAM NAME='JSON" + n + "' VALUE='" + jsonArr[n] + "'>" );
	  }

	  upload.document.write( "<PARAM NAME='JSESSIONID' VALUE='" + jses + "'>" );
	  upload.document.write( "<PARAM NAME='URL' VALUE='" + url + "'>" );
	  upload.document.write( "<PARAM NAME='contextPath' VALUE='" + ctx + "'>" );
	  upload.document.write( "<PARAM NAME='PROC_ID'  VALUE='" + pid + "'>" );
	  upload.document.write( "<PARAM NAME='sdmUserSessionKey'  VALUE='" + key + "'>" );
	  upload.document.write( "<PARAM NAME='logLevels'  VALUE='" + logLevels + "'>" );
	  upload.document.write( "<PARAM NAME='fileSelectionType'  VALUE='" + fileSelectionType + "'>" );
	  upload.document.write( "</APPLET>" );
	  upload.document.write( '</BR>' );
	  upload.document.write( ' <INPUT TYPE="BUTTON" ID="bb" ONCLICK="window.close()" STYLE="visibility:hidden;float:right" VALUE="Close"></INPUT>' );
	  upload.document.write( ' <SCRIPT> function closeAppletWindow(win){ window.opener=top; window.close();}</SCRIPT>' );
	  upload.document.write( ' <SCRIPT> function closeApplet(win){ document.getElementById("bb").style.visibility= "visible";}</SCRIPT>' );
	  upload.document.write( ' <SCRIPT> function displayMessage(msg){ alert(msg); return true;}</SCRIPT>' );
	  upload.document.write( ' <SCRIPT> function winX(){ if(document.getElementById("bb").style.visibility == "hidden"){ if(confirm("WARNING: Closing this window while files are being uploaded will result in data loss or process failure!!!")) { window.opener.terminateApplet(document.efsUploader.getParameter("PROC_ID")); document.efsUploader.setStopped(true); }; return false; } }</SCRIPT>' );

	  upload.document.write( ' <SCRIPT> window.onbeforeunload=winX;</SCRIPT>' );
	  upload.document.write( '</BODY> </HTML>' );
	  upload.document.close( )
}

function terminateApplet(pid, json) {
		terminate(pid , json);
}


/** Adds flag to disable validation and Submits the form
@param el is the element triggering the submission.
*/

function smSubmitOnEvent( el ) {
  var frm = el.form;
  if ( frm == null ) {
    alert( "smSubmitForm: no form found." );
    return;
  }
  //add hidden parameter
  var hidden = document.createElement( 'input' );
  hidden.setAttribute( 'name', 'SM_DISABLE_VALIDATION' );
  hidden.setAttribute( 'type', 'hidden' );
  hidden.setAttribute( 'value', 'DISABLE' );
  frm.appendChild( hidden );

  frm.submit( );
}

/** Submits the form of the given element.
    @param el is the element triggering the submission.
    @param target is the name of the target window (optional).
 */

function smSubmitForm( el, target ) {
  var frm = el.form;
  if ( frm == null ) {
    alert( "smSubmitForm: no form found." );
    return;
  }
  if ( target ) {
    frm.target = target;
  }
  frm.submit( );
}

/** Searches for the "div" ending with the given id. If found its visibility
    will be toggled.
 */
function smShowAdvanced( check, divId ) {

  var divs = document.getElementsByTagName( "div" );
  var ext = ":" + divId;
  var found = false;
  for ( var i = 0; i < divs.length; i++ ) {
    var d = divs[i];
    var id = d.id;
    if ( !id )
      continue;
    if ( id.indexOf( ext ) != id.length - ext.length )
      continue;
    found = d;
    break;
  }
  if ( !found ) {
    alert( divId + "not found" );
    return;
  }

  var style = found.style;
  style.display = check.checked ? "block" : "none";
}

/** Adds a new option to the given list. The value is ignored if it's already
 *  part of the list.
 */
function smAddToList( list, text, value ) {
  var opt = list.options;
  var len = opt.length;
  // check if value already exists
  for ( var i = 0; i < len; i++ ) {
    if ( opt[i].value == value )
      return;
  }

  var o = new Option( );
  o.text = text;
  o.value = value;
  o.selected = false;
  opt[len] = o;
  len++;
  for ( var i = 0; i < len; i++ ) {
    for ( var j = i + 1; j < len; j++ ) {
      if ( opt[i].text > opt[j].text ) {
        var tmp = opt[i].value;
        opt[i].value = opt[j].value;
        opt[j].value = tmp;
        var tmp = opt[i].text;
        opt[i].text = opt[j].text;
        opt[j].text = tmp;
        var tmp = opt[i].selected;
        opt[i].selected = opt[j].selected;
        opt[j].selected = tmp;
      }
    }
  }
}

/** Copies the values from the given list into the hidden field.
 *  The values will be separated with "\t" characters.
 */
function smListToHidden( list, hidden ) {
  var opt = list.options;
  var len = opt.length;

  var value = "";
  for ( var i = 0; i < len; i++ ) {
    if ( i > 0 )
      value += "\t";
    value += opt[i].value;
  }
  hidden.value = value;
}

/** Removes the given value from the given list.
 */
function smRemoveValue( list, value ) {
  var opt = list.options;
  var len = opt.length;
  for ( var i = 0; i < len; i++ ) {
    if ( opt[i].value != value )
      continue;
    for ( var j = i + 1; j < len; j++ ) {
      opt[j - 1].text = opt[j].text;
      opt[j - 1].value = opt[j].value;
      opt[j - 1].selected = opt[j].selected;
    }
    opt.length--;
    break;
  }
}

/** Removes all selected values from the given list.
 */
function smRemoveSelected( list ) {
  var opt = list.options;
  var len = opt.length;
  for ( var i = 0; i < len; i++ ) {
    if ( !opt[i].selected )
      continue;
    smRemoveValue( list, opt[i].value );
    len--;
    i--;
  }
}

/** Opens a new window with the given url.
 *  @param url is the URL to be displayed in the new window.
 *  @param name is the optional name of the new window.
 *  @param w is the optional width of the new window.
 *  @param h is the optional height of the new window.
 *  @return the method returns false for easier use in onclick handlers.
 */
function smShowPopup( url, name, postData,w, h ) {

  postData = eval('('+postData+')');
  if ( !name )
    name = "info";
  if ( !w )
    w = 640;
  if ( !h )
    h = 480;
  if(postData == null || postData.postURL ==null || postData.postURL ==""){
	  window.open(url,name,'scrollbars=yes,resizable=1,menubar=no,width="+w+",height="+h+"');
  }
  else{
	  submitRequest(postData.EncryptedUID,postData.SaltValue,postData.postURL,postData.refer,postData.product);
  }
  // iframe.src = url; doesn't work in FireFox for security reasons.

  return false;
}

function submitRequest(encryptedUID,saltValue,postURL,refer,product ){
    var sData;
    sData = "<form name='loginform' id='loginform' action='" + postURL + "' method='post'>";
    sData = sData + "<input type='hidden' name='EncryptedUID' id='EncryptedUID' class='input' value='" + encryptedUID + "' />";
    sData = sData + "<input type='hidden' name='SaltValue' id='SaltValue' class='input' value='" + saltValue + "' />";
	sData = sData + "<input type='hidden' name='refer' id='refer' class='input' value='" + refer + "' />";
	sData = sData + "<input type='hidden' name='product' id='product' class='input' value='" + product + "' />";
    sData = sData + "<input type='submit' name='wp-submit' id='wp-submit' value='Login' style=" + "display:none" + " />";
    sData = sData + "</form>";
    sData = sData + "<script type='text/javascript'>";
    sData = sData + "document.loginform.submit();"+ "</script>";
    //alert(sData);
    OpenWindow=window.open("", "_blank");
    OpenWindow.document.write(sData);
    OpenWindow.document.close();
  
}
/** Returns the context path of the web application.
 *  @return e.g. /SimManager
 */
function getContextPath( ) {
	return CSC.getContextPath();
}

/** Searches for the "div" ending with the given id. If found its visibility
    will be toggled.
 */
function showAdvanced( button ) {

  var id = button.id;

  var divs = document.getElementById( id + "_div_ID" );
  var hidd = document.getElementById( id + "_hidden_toggle" );

  var imageId = id + "_graphic_image";
  var imageForceId = imageId.substr( imageId.indexOf( "__" ), imageId.length );
  var image = document.getElementById( imageForceId );
  var imageVal = image.src;
  var hiddImage = document.getElementById( id + "_hidden_image_path" );
  var val = hidd.value;
  var style = divs.style;
  var theme = document.getElementById( id + "_hidden_pref_theme" );
  var themeval = theme.value;

  style.display = ( val == "collapse" ) ? "block" : "none";

  if ( imageVal.indexOf( "down.gif" ) > 1 ) {
    imageSel = imageVal.substr( 0, imageVal.indexOf( "down.gif" ) );
  }

  if ( imageVal.indexOf( "up.gif" ) > 1 ) {
    imageSel = imageVal.substr( 0, imageVal.indexOf( "up.gif" ) );
  }

  if ( val == "expand" ) {
    hidd.value = "collapse";
    hiddImage.value = "/themes/" + themeval + "/images/down.gif";
    image.src = imageSel + "down.gif";
    return false;
  }

  if ( val == "collapse" ) {
    hidd.value = "expand";
    hiddImage.value = "/themes/" + themeval + "/images/up.gif";
    image.src = imageSel + "up.gif";
    return false;
  }
  return false;
}

/** For File Upload */
function fpSubmitOnEvent( el ) {
  var frm = el.form;
  if ( frm == null ) {
    alert( "smSubmitForm: no form found." );
    return;
  }
  //add hidden parameter
  var hidden = document.createElement( 'input' );
  hidden.setAttribute( 'name', 'SM_DISABLE_VALIDATION' );
  hidden.setAttribute( 'type', 'hidden' );
  hidden.setAttribute( 'value', 'DISABLE' );
  frm.appendChild( hidden );
  Richfaces.showModalPanel('SMSTATUSDLG-status');
  jsf.ajax.request(el, null, {'javax.faces.behavior.event': 'action', 'execute': '@all','render':'[]'});

 // frm.submit( );
}
/** for File Upload Remove Button. This is required to get validaton called */
function smClearHidden( frm, id ) {

  var lastIndex = id.lastIndexOf( "-v" );
  id = id.substring( 0, lastIndex );
  var hidden_file = document.getElementById( id + "_hidden" );
  hidden_file.value = "";

  return false;
}

/**
 * To enable dynamic scrollbars to the Dialog
 */
function setDlgSize() {
	var wt = jQueryEnterprise(window).width();
	 var hght=jQueryEnterprise(window).height();
	
	var edithome=jQueryEnterprise('[id$=HomepageEditDialog_content_scroller]');
	if(edithome.length>0){
		var height=edithome.height();
		edithome.height(height+50);
	}
	
	jQueryEnterprise('[id$=ctionDialog_content_scroller]').css({
		'max-height' : (hght - 100),
		'max-width' : (wt - 40)
	});
	
	jQueryEnterprise('[id$=ctionDialog_shadow]').css({
		'max-height' : (hght - 100)

	});
	jQueryEnterprise('[id$=ctionDialog_container]').css({
		'max-height' : (hght - 100)

	});
	var iframe = jQueryEnterprise('.rf-pp-ifr');
	iframe.each(function(){		
		scr=jQueryEnterprise(this).parent().find('[id$=_content_scroller]' );
			 jQueryEnterprise(this).width(scr.width());
			 jQueryEnterprise(this).height(scr.height());

	});
	jQueryEnterprise('[id$=ParameterFilterDlg_container]').css({
  		'max-height' : (hght - 40),
  		'max-width' : (wt - 40)	
 		
	 });
}


 


/**
 * Trigger jQuery scripts - jQuery Starting point
 */
function initJQuery( ) {
  var wa = jQueryEnterprise('.NWRightPanel');
	if(wa.length <= 0 ) {
	 var banner = jQueryEnterprise('html');
	 banner.css({'overflow':'auto'});
  }	
  setTreePnlHeight( );
  setSODTreeScroll();
  setWorkAreaScroll( );
  setPageScroll();
  setProcessSODScroll();
  setTreeScrollPos();
  //setParseScroll();
  //This will be called from Materials widget.
  //setMatMaterialSODPageScroll();
  setMatMaterialComparePageScroll();
}

function resizeClipBoardAos(id){
	var ele = document.getElementById(id);
	ele = jQueryEnterprise(ele);
	var height = jQueryEnterprise(window).height();
	var width = jQueryEnterprise(window).width();
	var hgt = height - 40;
	var wt = width - 40;
	
	var div = ele.find("div.CLIPBOARDRESIZE");
	div.css("max-height", hgt-40);
	div.css("max-width", wt-40);
	div.width (wt-100);
	div.height (hgt-150);
	div.css({
		'overflow' : 'auto',
		'top' : '20px',
		'left' : '20px'
	});
	var div13 = ele.find("div.AOSLHS");
	var div3 = ele.find("div.AOSRHS");
	var div4 = ele.find("div[id$=':SearchWorkspaceAOS:searchPanel1']");
	if (div3.length>0  && div13.length>0 ) {
		div3.height(hgt - 200);
		div3.width((wt - 90) * 0.70);
		div3.css("overflowX", "auto");
		div3.css("overflowY", "auto");
		div13.height(hgt - 200);
		
		div4.attr('style', '');

		div13.width(((wt - 80) * 0.30));
		div13.css("overflowX", "auto");
		div13.css("overflowY", "auto");
		var __isIE =  navigator.appVersion.match(/MSIE/) != null;
		if(__isIE) //Hack for IE for flickerting scrollbar in AOS
			div13.css("overflowX", "scroll");
		RichFaces.$(id).resize(wt  , hgt);
		RichFaces.$(id).moveTo(10,10);
		var dialog = APP.getDialogData(id);
		var scrollPane = dialog.scrollPane;
		var popup = dialog.popup;
		var dlgShadow =dialog.shadow;
		var dlgContainer = dialog.container;
		var iframe = dlgContainer.find("iframe.rf-pp-ifr");
		var win = jQueryEnterprise(window);
		var h = win.height();
		var w = win.width();
		APP.addScrollToDialog(scrollPane,dlgContainer, dlgShadow,iframe, h , w);
	}
	
	 
}

function resizeAOS() {
	var height = jQueryEnterprise(window).height();
	var width = jQueryEnterprise(window).width();
	var aos= jQueryEnterprise("div.AOSRESIZE");
	var errAos = jQueryEnterprise("div.SMAdvancedObjectSelector");
    var err = errAos.find("td.GlobalError");
    if(err.length > 0){
        var t = errAos.find("table.GlobalMessages");
        var tR = t.parent().parent();
        tR.remove();
        alert(err.text());
    }
	aos.each(function(){
	var div16 = jQueryEnterprise(this).find("div[id$='-f:osDlg_osTbl']");
	var div2 = jQueryEnterprise(this).find("div[id$='_TRBSWp']");
	var div3 = jQueryEnterprise(this).find("div[id$=':SearchWorkspaceAOS:searchAreaScrollPane']");
	var div4 = jQueryEnterprise(this).find("div[id$=':SearchWorkspaceAOS:searchPanel1']");
	var div13 = jQueryEnterprise(this).find("div[id$=':SearchWorkspaceAOS:SearchWorkspaceAOSsws']");
	var div6 = jQueryEnterprise(this).find("div[id$='-f:objectSelectionTable_objectSelectionDialog']");
	var div11 = jQueryEnterprise(this).find("div[id$='-f:sw_Dlg_objectsTableAOS']");
	var div12 = jQueryEnterprise(this).find("div[id$='-f:objectSelector']");
	var div14 = jQueryEnterprise(this).find("table[id$='_osDlgContentTable']");
	var div1 = jQueryEnterprise(this);
	var div21 = jQueryEnterprise(this).find("div[id$='_content_scroller']");
	
	var hgt = height - 40;
	var wt = width - 40;
	if (div1.length>0) {
			div1.css("max-height", hgt);
			div1.css("max-width", wt);
			div1.width (wt-40);
			div1.height (hgt-40);

		div1.css({
			'overflow' : 'hidden',
			'top' : '20px',
			'left' : '20px'
		});
	}

	if (div11.length>0) {
		var oheight1 = div11.height();
		if (oheight1 < hgt) {
			div11.css("max-height", hgt);
		}
		var owidth1 = div11.width();
		
		if (owidth1 < wt) {
			div11.css("max-width", wt);
			div11.width (wt-40);
		}
	}
	if (div12.length>0) {
		var oheight2 = div12.height();
		if (oheight2 < hgt) {
			div12.css("max-height", hgt);
		}
		var owidth2 = div12.width();
		
		if (owidth2 < wt) {
			div12.css("max-width", wt);
			div12.width (wt-40);
		}
	}
	if (div14.length>0) {
		div14.css("width", wt-5);
	}
	if (div21.length>0) {
		div21.width (wt-40);
		div21.height (hgt-40);
		div21.css({
			'overflow' : 'hidden'
		});
	}
	if (div2.length>0) {
		div2.height(hgt - 180);
		div2.width(wt - 100);
	}
	if (div3.length>0  && div13.length>0 ) {
		div3.height(hgt - 200);
		div3.width((wt - 90) * 0.70);
		div4.attr('style', '');
		div3.css("overflowX", "auto");
		div3.css("overflowY", "auto");
		div13.height(hgt - 200);
		div13.width(((wt - 80) * 0.30));
		div13.css("overflowX", "auto");
		div13.css("overflowY", "auto");
		var __isIE =  navigator.appVersion.match(/MSIE/) != null;
		if(__isIE) //Hack for IE for flickerting scrollbar in AOS
			div13.css("overflowX", "scroll");
		
	}
	
	if (div6.length>0) {
		var oheight = div6.height();
		if (oheight < hgt) {
			div6.css("max-height", hgt);
		}
		var owidth = div6.width();
		if (owidth < wt) {
			div6.css("max-width", wt);
			div6.width(wt);
		}
	}
	});
	var compDialog= jQueryEnterprise("div.COMPONENTRESIZE");
	compDialog.each(function(){
		var div16 = jQueryEnterprise(this).find("div[id$='-f:osDlg_osTbl']");
		var div2 = jQueryEnterprise(this).find("div[id$='_TRBSWp']");
		var div3 = jQueryEnterprise(this).find("div[id$=':SearchWorkspaceAOS:searchAreaScrollPane']");
		var div4 = jQueryEnterprise(this).find("div[id$=':SearchWorkspaceAOS:searchPanel1']");
		var div13 = jQueryEnterprise(this).find("div[id$=':SearchWorkspaceAOS:SearchWorkspaceAOSsws']");
		var div5 = jQueryEnterprise(this).find("div[id$='_osDlgCDiv']");
		var div6 = jQueryEnterprise(this).find("div[id$='-f:objectSelectionTable_objectSelectionDialog']");
		var div10 = jQueryEnterprise(this).find("div[id$='_objectSelectionDialogCDiv']");
		var div7 = jQueryEnterprise(this).find("div[id$='wsmDialogCDiv']");
		var div11 = jQueryEnterprise(this).find("table[id$='_osDlgContentTable']");
		var offset = 60;
		var div1 = jQueryEnterprise(this);
		var div17 = jQueryEnterprise(this).find("div[id$='_content_scroller']");
		
		var hgt = height - 40;
		var wt = width - 40;
		if (div1.length>0) {
				div1.css("max-height", hgt);
				div1.css("max-width", wt);
				div1.width (wt-40);
				div1.height (hgt-40);

			div1.css({
				'overflow' : 'hidden',
				'top' : '20px',
				'left' : '20px'
			});
		}
		if (div17.length>0) {
			div17.width (wt-40);
			div17.height (hgt-40);
			div17.css({
				'overflow' : 'hidden'
			});
		}
		if (div5.length>0) {
			div5.css("max-height", hgt);
			div5.css("width", wt+5);
		}
		if (div11.length>0) {
			div11.css("width", wt-5);
		}
		if (div7.length>0) {
			var oheight = div7.height();
			if (oheight < hgt) {
				div7.css("max-height", hgt);
			}
			var owidth = div7.width();
			if (owidth < wt) {
				div7.css("max-width", wt);
			}
		}
		if (div2.length>0) {
			div2.height(hgt - 140);
			div2.width(wt - 60);
		}
		if (div3.length>0  && div13.length>0 ) {
			div3.height(hgt - 210);
			div3.width((wt - 75) * 0.75);
			div4.attr('style', '');
			div3.css("overflowX", "auto");
			div3.css("overflowY", "auto");
			div13.height(hgt - 210);
			div13.width(((wt - 65) * 0.25));
			div13.css("overflowY", "auto");
			div13.css("overflowX", "auto");
			var __isIE =  navigator.appVersion.match(/MSIE/) != null;
			if(__isIE){	//Hack for IE for flickerting scrollbar in AOS
				div13.css("overflowX", "scroll");
			}
		}
		if (div6.length>0) {
			var oheight = div6.height();
			if (oheight < hgt) {
				div6.css("max-height", hgt);
			}
			var owidth = div6.width();
			if (owidth < wt) {
				div6.css("max-width", wt);
			}
		}
		if (div10.length>0) {
			div10.css("max-height", hgt);
			div10.css("max-width", wt);
		}
		
		
	});
	
}

/** SIMMGR-44485 Current Unit System Toolbar hiding Process message content for first executed action **/
function setProcessSODScroll(){
	var processSOD = jQueryEnterprise('.processSOD');
	if(processSOD.length <= 0)return;
	var window_ht = jQueryEnterprise(window).height();
	var processSOD_ht = processSOD.height();
	if(processSOD_ht > window_ht){
		var diffHt = (processSOD_ht - window_ht) + 25;
		processSOD.css( {  'overflow-x' : 'auto','overflow-y' : 'auto','height' : window_ht + diffHt  +'px'} );
	}
}

function AOSValidator(btn,err){
	var aos = jQueryEnterprise("div.SMAdvancedObjectSelector");
	var treesel = aos.find(".spSelect");
	var searchsel = aos.find(".sr");
	var flag = false;
	if( treesel.length >0){
		flag = true
	}
	if( searchsel.text() >0){
		flag = true;
	}
	if(flag == false){
		alert(err);
		Richfaces.hideModalPanel ('SMSTATUSDLG-status');
		return false;
	}else
		return true;
	
}

/**
 * Dynamically Adds Scrollbars to the LH Tree
 */
function setTreePnlHeight( ) {
	setDlgSize();
	resizeAOS();
	  var scrollP = jQueryEnterprise( '.TreeResizeOnClient' );
	  var wa = jQueryEnterprise('.NWRightPanel');
	  var ht = jQueryEnterprise( window ).height( );
	  var wt = jQueryEnterprise( window ).width( );
	  if(scrollP.length > 0 ) {
			var banner= jQueryEnterprise('.BannerHeaderR4');
			var banHgt= banner.height();
			var gbread= jQueryEnterprise('.GlobalBreadcrumb');
			var gbrHgt= gbread.height();
			var footer= jQueryEnterprise('.SmFooter');
			var footerHgt= gbread.height();
			var navTree= jQueryEnterprise('.SMObjectTreeNavigation');
			var filter= navTree.height()-scrollP.height();
		  var scrollB = jQueryEnterprise('.ResizeOnClient');
		  scrollP.scroll( function( ) {
		    var scroller = jQueryEnterprise( this ).scrollTop( );
		    jQueryEnterprise( '#smTreeScrollPos' ).val( scroller );
		  } );
		  //----------------------------->
		  //TOOD 
		  //var treeHt = (ht-(banHgt+gbrHgt+footerHgt+filter)) - 50 +"px";
		  var treeHt = (ht-(banHgt+gbrHgt+footerHgt+filter)) - 22 +"px";
		  //----------------------------->
		  scrollP.height( treeHt ).css( {
		    'overflow' : 'auto',
		    'border-right' : '2px solid #ccc'
		  } );
		  
		  var treeWidth = wt * 0.15;
		  var treeResizedWidth = jQueryEnterprise('#smTreeResizedWidth').val();
		  if(treeResizedWidth > 0 ) {
			  scrollP.width(treeResizedWidth+"px");
			  scrollB.width(treeResizedWidth+"px");
		  }else{
			  scrollP.width(treeWidth+"px");
			  scrollB.width(treeWidth+"Px");
		  }
		  
		  var scrlHt = scrollP.height( );
		  
			  scrollB.resizable({
				  
				  'maxHeight' : scrlHt,
				  'minHeight' : scrlHt,
				
				  resize: function(event, ui) {
				    var wid = ui.size.width;
				    
				  	jQueryEnterprise('#smTreeResizedWidth').val(wid);
				  	scrollP.width(wid);
				  	scrollB.width(wid);
				  	var win = jQueryEnterprise( window );
				  	
				  	//----------------------------->
				  	//TOOD 
				  	//var rightPanelWd = win.width() - wid - 51;
				  	var rightPanelWd = win.width() - wid - 23 ;
				  	//-----------------------------<	
				  	wa.width(rightPanelWd+"px");

				  	if(wid > treeWidth )
				  		scrollP.css("width",scrollB.width()-5+"px");
				  }
			  });
		  
		  var scrolled = jQueryEnterprise( '#smTreeScrollPos' ).val( );
	
		  // Restore scroll position
		  if ( parseInt( scrolled ) > 0 ) {
		    scrollP.scrollTop( scrolled );
		    jQueryEnterprise( '#smTreeScrollPos' ).val( scrolled );
		  }
		  
		  var sb = jQueryEnterprise('.ResizeOnClient');
		  sb.find("div.ui-icon-gripsmall-diagonal-se").hide();
		  sb.css("height",scrollP.height()+40+"px");
		  scrollP.css("width",sb.width()-1+"px");
		  var banner = jQueryEnterprise('html');
		  var win = jQueryEnterprise( window );
		  var ht = win.height();
		  
		  
		  //-------------------------------------------->
		  //TODO 
		  //var pnlHt = (ht-(banHgt+gbrHgt+footerHgt+50))  +"px";
		  //var pnlWt = win.width() - scrollP.width()- 51; // 51 is adjustment
		  var pnlHt = (ht-(banHgt+gbrHgt+footerHgt+22))  +"px";
		  var pnlWt = win.width() - scrollP.width()- 23;
		  //--------------------------------------------<
		  var rightPanelWidth = pnlWt + "px";
		  
		  wa.scroll( function( ) {
			    var scroller = jQueryEnterprise(this).scrollLeft();
			    jQueryEnterprise('#smWorkAreaScrollPos').val(scroller);
		  });
		  
		  wa.height( pnlHt ).css( {
		    'overflow-x' : 'auto',
		    'overflow-y' : 'auto',
		    'width'      : rightPanelWidth
		  } );


	  }
}

/**
 * Set Scroll logic for the Work Area Panel.
 */
function setWorkAreaScroll( ) {
  var wa = jQueryEnterprise( '.WorkAreaScroll' );
  var sb = jQueryEnterprise( '.LHSStyle' );
  var win = jQueryEnterprise( window );
  var ht = win.height( );
  var pnlHt = ht - 100;
  
  //----------------------------------------------->
  //TODO
  //var pnlWt = win.width( ) - sb.width( ) - 50; // 50 is adjustment
  var pnlWt = win.width( ) - sb.width( ) - 35; // 50 is adjustment
  //-----------------------------------------------< 
  if(pnlWt < 0){
	  pnlWt = -(pnlWt);
  }
  if(pnlWt > 100)
	  wa.css( {  'overflow-x' : 'auto','overflow-y' : '','width' : pnlWt+'px','height' : pnlHt+'px'} );
}

/**
* Dynamically Adds Scrollbars to the LH Tree
*/
function setSODTreeScroll() {
	var tableVar  = jQueryEnterprise('.SMWTKObjectsTable');
	var scrollP = jQueryEnterprise( '.SodTreeResizeOnClient' );
	scrollP.scroll( function( ) {
		var scroller = jQueryEnterprise( this ).scrollTop( );
		jQueryEnterprise( '#smTreeScrollPos' ).val( scroller );
	} );

	var tableHeight =   tableVar.height();
	var tableWidth = tableVar.width();
	var width = tableWidth * 0.25;
	scrollP.width(width);
	scrollP.height( tableHeight ).css( {
		'overflow' : 'auto',
		'border-right' : '2px solid #ccc'
	} );

	var scrolled = jQueryEnterprise( '#smTreeScrollPos' ).val( );
	// Restore scroll position
	if ( parseInt( scrolled ) > 0 ) {
		scrollP.scrollTop( scrolled );
		jQueryEnterprise( '#smTreeScrollPos' ).val( scrolled );
	}
}

/**
 * Import And Simulate Scrollbars
 * @return
 */
function setPageScroll() {
	
	 var wa = jQueryEnterprise('.NWRightPanel');
	 var banner = jQueryEnterprise('html');
	 if(wa.length<=0){
		 banner.css({'overflow':'auto'});
	 }
	 else{
		 var __isIE =  navigator.appVersion.match(/MSIE/) != null;
		 
		 if(__isIE){
			 var __IEVersion = __getIEVersion();
			 if(__IEVersion<=8){
				 banner.css({'overflow':'auto'});
			 }
			 else
				 banner.css({'overflow':'hidden'});
		 }
		 else
			 banner.css({'overflow':'hidden'});
	 }
    var browserScroll = jQueryEnterprise('.HideBrowseScroll');
  
	if(browserScroll.length > 0 ) {
	 banner.css({'overflow':'hidden'});
	}
	var scrollP  = jQueryEnterprise('.PageScroll');
	var simDialog=jQueryEnterprise("div .SG_HANDLE_SIMULATE_SCROLL");
	if(simDialog==null){		
		scrollP.scroll( function( ) {
			var scroller = jQueryEnterprise( this ).scrollTop( );
			jQueryEnterprise('#smTreeScrollPos').val( scroller );
		} );

		var height = jQueryEnterprise(window).height();
		var pnlHt =  height * 0.65;
		var width = jQueryEnterprise( window ).width() * 0.80;
		scrollP.width(width);
		scrollP.height( pnlHt ).css( {
			'overflow-y' : 'auto',
			'overflow-x' : 'hidden'
		} );
	}
	else{
		var scrol=simDialog.find('[id$=_content_scroller]');
		var shdw=simDialog.find('[id$=_shadow]');
		simDialog.height(scrol.height());
		shdw.height(scrol.height());
		simDialog.width(scrol.width());
		shdw.width(scrol.width()-30);
	}
	var scrolled = jQueryEnterprise( '#smTreeScrollPos').val( );
	// Restore scroll position
	if ( parseInt( scrolled ) > 0 ) {
		//scrollP.scrollTop( scrolled);   // This works for FF but not for IE
		scrollP.animate({scrollTop: scrolled},0);  // For IE6 and FF
		jQueryEnterprise( '#smTreeScrollPos' ).val( scrolled );
	}
}
 
 function setMatMaterialSODPageScroll() {
    var browserScroll = jQueryEnterprise('.HideBrowseScroll');
    var scrollP  = jQueryEnterprise('.MaterialSODScroll');
    if(scrollP.length > 0 ) {
	    var banner = jQueryEnterprise('html');
		banner.scrollTop(APP.smBrowserScroll.top);
    	banner.scrollLeft(APP.smBrowserScroll.left);

    if(browserScroll.length > 0 ) {
	     scrollP.css({
	        'overflow-y' : 'hidden',
	        'overflow-x' : 'hidden' 
	    });
    }
    
    scrollP.scroll( function( ) {
        var scroller = jQueryEnterprise( this ).scrollTop( );
        jQueryEnterprise('#smTreeScrollPos').val( scroller );
    } );
	var c = scrollP.children();
	
    var height = jQueryEnterprise(window).height();
    //var pnlHt =  height * 0.65;
    var width = jQueryEnterprise( window ).width()* 0.95;
 	var horizontal = (c.width() < 1700) ? "hidden" : "auto";
  	if(c.width() < 1700)
  		scrollP.width(width);
    //scrollP.height( pnlHt );
    banner.css( {
        'overflow-y' : 'auto',
        'overflow-x' : 'auto' 
    } );

    var scrolled = jQueryEnterprise( '#smTreeScrollPos').val( );
    // Restore scroll position
    if ( parseInt( scrolled ) > 0 ) {
        //scrollP.scrollTop( scrolled);   // This works for FF but not for IE
        scrollP.animate({scrollTop: scrolled},0);  // For IE6 and FF
        jQueryEnterprise( '#smTreeScrollPos' ).val( scrolled );
    }
}
}


 function setMatMaterialComparePageScroll() {
     var browserScroll = jQueryEnterprise('.HideBrowseScroll');
	 var scrollP  = jQueryEnterprise('.MaterialCompareScroll');
	if(scrollP.length > 0 ) {
		var banner = jQueryEnterprise('html');
   	 banner.scrollTop(0);
     banner.scrollLeft(0);
			if(browserScroll.length > 0 ) {
			     scrollP.css({
			        'overflow-y' : 'hidden',
			        'overflow-x' : 'hidden' 
			    });
		    }
		   
		    scrollP.scroll( function( ) {
		        var scroller = jQueryEnterprise( this ).scrollTop( );
		        jQueryEnterprise('#smTreeScrollPos').val( scroller );
		    } );
			var c = scrollP.children();
		    var height = jQueryEnterprise(window).height();
		   // var pnlHt =  height * 0.60;
		    //var width = jQueryEnterprise( window ).width() * 0.95;
			//var horizontal = (c.width() < 1700) ? "hidden" : "auto";
			//if(c.width() < 1700){
		  	//	scrollP.width(width);
			//}	
		    banner.css( {
		        'overflow-y' : 'auto',
		        'overflow-x' : 'auto' 
		    } );
		
		    var scrolled = jQueryEnterprise( '#smTreeScrollPos').val( );
		    // Restore scroll position
		    if ( parseInt( scrolled ) > 0 ) {
		        //scrollP.scrollTop( scrolled);   // This works for FF but not for IE
		        scrollP.animate({scrollTop: scrolled},0);  // For IE6 and FF
		        jQueryEnterprise( '#smTreeScrollPos' ).val( scrolled );
		    }
		}
 }
 
 function OnSelectFocus(ssfsList) {
	
 	 var ssfsScroll = jQueryEnterprise('.SSFSScrollPane');
 	 	
 	 	//On focus of Selectbox, making scroll position 
 	    //of DIV to very left i.e 0 if it is not. The reason behind
 	    //is, in this scenario we are fixing the size of Selectbox 
 	    //to 8 and if the size of items in Selecbox is greater than 8 
 	    //and to implement downarrow key and uparrow key 
 	    //functionality, the vertical scrollbar in selectbox will
 	    //be visible if the horizontal scrollbar of DIV is exremely right.
 	    if (ssfsScroll.scrollLeft() != 0)
	    {
 	    	ssfsScroll.scrollLeft(0);
	    }

 	 if( ssfsList.options.length > 10)
 	 {
 		// ssfsList.focus();
 		 ssfsList.size=ssfsList.options.length;
 	 }else {
 		ssfsList.size=10;
 	 }
 	return true;
 }
 
 /** maintians the tree scroll position for Dialog */
 function setTreeScrollPos() {
  	 var scrollP = jQueryEnterprise( '.treeScrollPosStyle' );
  	 if(scrollP.length > 0 ) {
  		 scrollP.scroll( function( ) {
  			var scroller = jQueryEnterprise( this ).scrollTop( );
  			jQueryEnterprise( '#smTreeScrollPos' ).val( scroller );
  		 });
  		 
  		 var scrolled = jQueryEnterprise('#smTreeScrollPos').val();
  		  // Restore scroll position
  		 if ( parseInt( scrolled ) > 0 ) {
  		    scrollP.scrollTop( scrolled );
  		    jQueryEnterprise('#smTreeScrollPos').val(scrolled);
  		 }
  	 }
 }
 

function setParseScroll() {
    var browserScroll = jQueryEnterprise('.HideBrowseScroll');
	if(browserScroll.length > 0 ) {
	 var banner = jQueryEnterprise('html');
	 banner.css({'overflow':'hidden'});
	}
	
	var scrollP  = jQueryEnterprise('.ParseScroll');
	scrollP.scroll( function( ) {
		var scroller = jQueryEnterprise( this ).scrollTop( );
		jQueryEnterprise('#smTreeScrollPos').val( scroller );
	} );
	//alert("Hi");
	var height = jQueryEnterprise(window).height();
	var pnlHt =  height * 0.65;
	var width = jQueryEnterprise( window ).width() * 0.75;
	scrollP.width(width);
	scrollP.height( pnlHt ).css( {
		'overflow-y' : 'auto',
		'overflow-x' : 'hidden'
	} );

	
	var scrollX  = jQueryEnterprise('.TablexScroll');
	scrollX.scroll( function( ) {
		var scroller = jQueryEnterprise( this ).scrollTop( );
		jQueryEnterprise('#smTreeScrollPos').val( scroller );
	} );
	//alert("Hi");
	var height = jQueryEnterprise(window).height();
	var pnlHt2 =  pnlHt * 0.60;
	var width2 = width * 0.40;
	scrollX.width(width2);
	scrollX.height( pnlHt2 ).css( {
		'overflow-y' : 'auto',
		'overflow-x' : 'auto'
	} );
	
	var scrolled = jQueryEnterprise( '#smTreeScrollPos').val( );
	// Restore scroll position
	if ( parseInt( scrolled ) > 0 ) {
		//scrollP.scrollTop( scrolled);   // This works for FF but not for IE
		scrollP.animate({scrollTop: scrolled},0);  // For IE6 and FF
		jQueryEnterprise( '#smTreeScrollPos' ).val( scrolled );
	}
	
	 var wa = jQueryEnterprise('#[id*=:mainScrollPane]' );
	 var height = jQueryEnterprise(window).height();
		var pnlHt =  height * 0.65;
		wa.height(pnlHt);
		wa.css( {
			'overflow-x' : 'auto'
		} );
/*		 var wap = jQuery('#[id*=:workAreaPanel]' );
		 var widthwap=wa.width();
			wap.width(widthwap+30);*/
}

function submitWizard( e ) {
  var frm = e.form;
  if ( frm == null ) {
    alert( "smSubmitForm: no form found." );
    return;
  }
  //add hidden parameter
  var hidden = document.createElement( 'input' );
  hidden.setAttribute( 'name', 'RW_SECTION_DATA' );
  hidden.setAttribute( 'type', 'hidden' );
  // FF uses frames[0], IE uses frames[1] 
  var jsonString;
  if (window.frames[0].submitChanges)
     jsonString = window.frames[0].submitChanges();
  else if (window.frames[1].submitChanges)
     jsonString = window.frames[1].submitChanges();
  
  if (!jsonString) {
	  Richfaces.hideModalPanel("SMSTATUSDLG-status");
	  return false;
  }
  
  hidden.setAttribute( 'value', jsonString );
  frm.appendChild( hidden );
  return true;
}

/** Find the absolute position of the element from another element x
 *     var pos = getElementAbsolutePos(myElement);     
 *     window.alert("Element's left: " + pos.x " and top: " + pos.y);   
 * 
 *  jQuery 1.5+ has this capability but we are using jQuery 1.4.2 which does not.  When
 *  we update to jQuery 1.5+, the following code can be removed.
 */  
function __getIEVersion() {
    var rv = -1; // Return value assumes failure.
    if (navigator.appName == 'Microsoft Internet Explorer') {
        var ua = navigator.userAgent;
        var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
        if (re.exec(ua) != null)
            rv = parseFloat(RegExp.$1);
    }
    return rv;
}

function __getOperaVersion() {
    var rv = 0; // Default value
    if (window.opera) {
        var sver = window.opera.version();
        rv = parseFloat(sver);
    }
    return rv;
}

var __userAgent = navigator.userAgent;
var __isIE =  navigator.appVersion.match(/MSIE/) != null;
var __IEVersion = __getIEVersion();
var __isIENew = __isIE && __IEVersion >= 8;
var __isIEOld = __isIE && !__isIENew;

var __isFireFox = __userAgent.match(/firefox/i) != null;
var __isFireFoxOld = __isFireFox && ((__userAgent.match(/firefox\/2./i) != null) || (__userAgent.match(/firefox\/1./i) != null));
var __isFireFoxNew = __isFireFox && !__isFireFoxOld;

var __isWebKit =  navigator.appVersion.match(/WebKit/) != null;
var __isChrome =  navigator.appVersion.match(/Chrome/) != null;
var __isOpera =  window.opera != null;
var __operaVersion = __getOperaVersion();
var __isOperaOld = __isOpera && (__operaVersion < 10);
var __isLegacyIE = __isIE && __IEVersion < 11;
var __isIE1 = __isIEBrowser();

function __isIEBrowser(){
	var isIE=navigator.appVersion.match(/MSIE/) != null
	if(isIE)
		return true;
	isIE=navigator.appVersion.match(/Trident/) != null
	return isIE;
	
}

function __isIECompatibilityMode(){
	var isIE = __isIEBrowser();
	if(isIE){
		return navigator.appVersion.match(/compatible/) != null;		
	}	
}

function __parseBorderWidth(width) {
    var res = 0;
    if (typeof(width) == "string" && width != null && width != "" ) {
        var p = width.indexOf("px");
        if (p >= 0) {
            res = parseInt(width.substring(0, p));
        }
        else {
     		//do not know how to calculate other values (such as 0.5em or 0.1cm) correctly now
    		//so just set the width to 1 pixel
            res = 1; 
        }
    }
    return res;
}


//returns border width for some element
function __getBorderWidth(element) {
	var res = new Object();
	res.left = 0; res.top = 0; res.right = 0; res.bottom = 0;
	if (window.getComputedStyle) {
		//for Firefox
		var elStyle = window.getComputedStyle(element, null);
		res.left = parseInt(elStyle.borderLeftWidth.slice(0, -2));  
		res.top = parseInt(elStyle.borderTopWidth.slice(0, -2));  
		res.right = parseInt(elStyle.borderRightWidth.slice(0, -2));  
		res.bottom = parseInt(elStyle.borderBottomWidth.slice(0, -2));  
	}
	else {
		//for other browsers
		res.left = __parseBorderWidth(element.style.borderLeftWidth);
		res.top = __parseBorderWidth(element.style.borderTopWidth);
		res.right = __parseBorderWidth(element.style.borderRightWidth);
		res.bottom = __parseBorderWidth(element.style.borderBottomWidth);
	}
   
	return res;
}


//returns the absolute position of some element within document
function getElementAbsolutePos(elemID) {
	var element;
	if (typeof(elemID) == "string")	{
		element = document.getElementById(elemID);
	}
	else {
		element = elemID;
	}

	var res = new Object();
	res.x = 0; res.y = 0;
	if (element !== null) {
    	res.x = element.offsetLeft;

		var offsetParent = element.offsetParent;
		var offsetParentTagName = offsetParent != null ? offsetParent.tagName.toLowerCase() : "";

        if (__isIENew  && offsetParentTagName == 'td') {
		    res.y = element.scrollTop;
		}
		else {
		    res.y = element.offsetTop;
		}
    	
		var parentNode = element.parentNode;
		var borderWidth = null;

		while (offsetParent != null) {
			res.x += offsetParent.offsetLeft;
			res.y += offsetParent.offsetTop;
			
			var parentTagName = offsetParent.tagName.toLowerCase();	

			if ((__isIEOld && parentTagName != "table") || (__isFireFoxNew && parentTagName == "td")  || __isChrome) {		    
				borderWidth = __getBorderWidth(offsetParent);
				res.x += borderWidth.left;
				res.y += borderWidth.top;
			}
		    
			if (offsetParent != document.body && offsetParent != document.documentElement) {
				res.x -= offsetParent.scrollLeft;
				res.y -= offsetParent.scrollTop;
			}


			//next lines are necessary to fix the problem with offsetParent
   			if (!__isIE && !__isOperaOld || __isIENew) {
    			while (offsetParent != parentNode && parentNode !== null) {
					res.x -= parentNode.scrollLeft;
					res.y -= parentNode.scrollTop;
					if (__isFireFoxOld || __isWebKit) {
						borderWidth = __getBorderWidth(parentNode);
						res.x += borderWidth.left;
						res.y += borderWidth.top;
					}
    				parentNode = parentNode.parentNode;
    			}    
			}

   			parentNode = offsetParent.parentNode;
    		offsetParent = offsetParent.offsetParent;
		}
	}
    return res;
}

function getElementAbsolutePositionWidthHeight(elementId) {
	var element;
	if (typeof(elementId) == "string")	
		element = document.getElementById(elementId);
	else 
		element = elementId;
	var pos = getElementAbsolutePos(element); 
	var objectsXYWH = new Object();
	objectsXYWH.x = pos.x;
	objectsXYWH.y = pos.y;
	objectsXYWH.w = element.clientWidth;
	objectsXYWH.h = element.clientHeight;
	return objectsXYWH;
}

// function to adjust calendar popup position
function adjustCalendarPopupPos(dialogID,calendarPanelID) {
	var element = document.getElementById(calendarPanelID);

	var dialogXYWH = getElementAbsolutePositionWidthHeight(dialogID);
    var scrollXYWH = getElementAbsolutePositionWidthHeight(calendarPanelID);   
    
    var dialogXplusW = dialogXYWH.x + dialogXYWH.w;
    var dialogYplusH = dialogXYWH.y + dialogXYWH.h;
    var scrollXplusW = scrollXYWH.x + scrollXYWH.w;
    var scrollYplusH = scrollXYWH.y + scrollXYWH.h;
    
    var xxx = element.style.left.replace(/px,*\)*/g,"")
    var yyy = element.style.top.replace(/px,*\)*/g,"")
    if (scrollXplusW > dialogXplusW) 
    	element.style.left = element.offsetLeft - (scrollXplusW - dialogXplusW) + "px";
    if (scrollYplusH > dialogYplusH) 
    	element.style.top = element.offsetTop - (scrollYplusH - dialogYplusH) + "px";
	
}

/** start preview html for a report */
function startPreviewHtml(context,downloadUrl){
	var protocol = location.protocol + "//" + location.host;
	var url = protocol + context+downloadUrl;
	window.open(url, "_blank");
}

/** display alert */
function displayAlert(message){
	alert(message);
}

function smShowHelp(topic, page, failOnError,displayURL) {
    // var div = jQueryEnterprise("<div>"+topic+": "+page+"</div>"); 
    var baseURL = "../../servlet/help/"+topic;
    var URL = baseURL+"/"+page+".html";    
    var fallback = smShowHelpError;
    
    if(!failOnError) {
        fallback = function(req, msg, exp) {
            if(req.status == 404) {
            	if(null != displayURL)  {
            		smShowPopup(displayURL);
            	}else{
           			 smShowHelp(topic, 'default', true);
           		 }
            }
            else {
            	smShowHelpError(req, msg, exp);
            }
        };
    }

    jQueryEnterprise.ajax({ 
        url: URL,
        ascync: false,
        cache: false,
        dataType: 'html',
        success: function(html) {
            var base = window.location.href;
            var idx = base.lastIndexOf('/');
            base = base.substring(0, idx);
            
            var div = jQueryEnterprise("<div class='SMHelp'>"+html+"</div>")
            div.find("img").each(function(i) {
                var src = this.src;
                if(src.indexOf(base) == 0) {
                    src = baseURL+src.substring(idx);
                    this.src = src;
                }
            } );
            div.dialog({ modal: true, title: "Help", //  show: 'blind', 
                         width: 640, height: 480
            });
        }
,
        error: fallback
    });
}

function smShowHelpDialog(html) {
    var base = window.location.href;
    var idx = base.lastIndexOf('/');
    base = base.substring(0, idx);
    
    var div = jQueryEnterprise("<div class'SMHelp'>"+html+"</div>")
    div.find("img").each(function(i) {
        var src = this.src;
        if(src.indexOf(base) == 0) {
            src = baseURL+src.substring(idx);
            this.src = src;
        }
    } );
    div.dialog({ modal: true, title: "Help", //  show: 'blind', 
                 width: 640, height: 480
    });
}


	function insertAtCursor(myField, myValue) {
	    // IE support
	    if (document.selection) {
	          myField.focus();
	          sel = document.selection.createRange();
	          sel.text = myValue;
	          sel.collapse(false);
	          sel.select();
	    }
	    // MOZILLA/NETSCAPE support
	    else if (myField.selectionStart || myField.selectionStart == 0) {
	             var val = myField.value;
	             var start = myField.selectionStart;
	             myField.value = val.slice(0, start) + "\n" + val.slice(myField.selectionEnd);
	             myField.selectionStart = myField.selectionEnd = start + 1;
	    } else {
	          myField.value += myValue;
	          myField.value = myField.value.replace(/(\r\n)|(\n)/g, "<br/>");
	    }
	}

function smShowHelpError(req, msg, exp) {
    alert("Help returned an error: "+msg); // TODO better error message
}
/**
 * jsfunction for EasySearch
 */
function ChangeEasySearch(elem,cId){
	  var val = elem.value;
	  if(val == "More"){
		  easySearch(cId,val);
	  }
	}

/**
 * To disable ViewAll if no records found
 */
function handleViewAll(ele){
	var jEle = jQueryEnterprise(ele);
	var parentDiv = jEle.parentsUntil("div.dummyHomeGadget");
	var clickable = false;
	var rowEven;
	parentDiv.each(function(){
		rowEven = jQueryEnterprise(this).find("tr.ModBodyRowEven");
		if(rowEven.length > 0 ) clickable = true;
		});
	if(!clickable)return false;
	Richfaces.showModalPanel('SMSTATUSDLG-status');
    return true;
}

function testColorChange(ele){
	var jTr = jQueryEnterprise(ele).parent().parent();
	var jGrid = jTr.parent();
	jGrid.find("tr").css("background-color", "");
	//jGrid.find("tr").removeClass("ModHigh");
	//jTr.addClass("ModHigh");
	jTr.css("background-color", "yellow");
	return true;
}

function smWorkSpaceTabHandler(el){
	 var jRoot = jQueryEnterprise("div[id='f:w:wm']");	 
	 var jbc = jRoot.find("table.GlobalBreadcrumb");
	 var jWS = jbc.find("td.GlobalBcInactiveHead");
	 
	 jWS.click(function(event){
		 var jTd= jQueryEnterprise(this);
		 var jInput = jTd.find("input");
		 var domInput = jInput[0]; 
		 if(domInput && event.target.tagName == 'TD')			 
			 domInput.onclick(); 
	//SIMMGR-43111 Menu options displaying while navigating to other tabs
	//	 event.stopImmediatePropagation();
	 });		 
}

function crossPlot(queryStr, ot) {
    var div = jQueryEnterprise("<div></div>");
    div.sdmMOD('showCrossPlotUI', div, queryStr, ot);
}

CSC = {
    getContainer: function(id) {
        id = id.replace(/:/g, "\\:");
        return jQueryEnterprise(jQueryEnterprise.find('#'+id));
    },
    getHidden: function(div) {
        var id = div.attr('id');
        id = id.replace(/:/g, "\\:");
        return div.find('#'+id+"_hidden");
    },
    getState: function(div) {
        var hid = CSC.getHidden(div);
        return eval('('+hid.val()+')');
    },
    saveState: function(div, state) {
        var s = JSON.stringify(state);
        var hid = CSC.getHidden(div);
        hid.val(s);
    },
    getBody: function(div) {
        var id = div.attr('id');
        id = id.replace(/:/g, "\\:");
        return div.find('#'+id+"_body");
    },
    FILE_SIZE: [ 'b', 'kB', 'MB', 'GB' ],
    formatSize: function(size) {
        var max = 1;
        for(var i = 0; i < CSC.FILE_SIZE.length; i++, max *= 1024) {
            var l = CSC.FILE_SIZE[i];
            if(size < 10*1024*max) return parseInt(size/max)+"\u00a0"+l;
        }
        return parseInt(size/max)+"\u00a0TB";
    },
    getFile: function(url) {
        var file = false;
        jQueryEnterprise.ajax({
            url: url, type: 'GET', dataType: 'text',
            async: false, cache: SM_FILE_AJAX_CACHE,
            success: function(text) { file = text; }
        });
        return file;
    },
    getContextPath: function() {
        var p = window.location.pathname;
        var idx = p.substring(1).indexOf('/');
        return idx == -1 ? p : p.substring(0, idx+1);
    },
    newRpcClient: function() {
        return new JSONRpcClient(CSC.getContextPath()+"/json-rpc");
    },
    esc: function(text) {
        return text.replace(/&/g, "&amp;").replace(/"/g, "&quot;")
            .replace(/'/g, "&#39;")
            .replace(/</g, "&lt;")
            .replace(/>/g, "&gt;");
    },
    rest: function(cmd, args, cb, error) {
        if(!error) {
            error = function(xhr, status, e) {
                switch(xhr.status) {
                    case 401:
                    default:
                        alert("error ("+cmd+"): "+xhr.status+": "+e);
                        break;
                }
            };
        }
        
        var url = CSC.getContextPath()+"/servlet/rest/"+cmd;
        jQueryEnterprise.ajax({
            url: url, data: args, traditional: true,
            type: 'POST', dataType: 'text',
            async: true, cache: false,
            success: cb,
            error: error
        });
    },
    showInfo: function(title, text, width, type) {
        if(!type) type = 'info';
        var dia = "<div class='ModDialog'><img></img>&nbsp;<span></span></div>";
        dia = jQueryEnterprise(dia);
        dia.find('span').text(text);
        dia.find('img').attr('src', CSC.getContextPath()+"/servlet/ilu?c=default&s=32&n="+type);
        
        var ok = CSC.i18n(['button.ok'])['button.ok'];
        var buttons = {};
        buttons[ok] = function() { dia.dialog('close'); };
        
        dia.dialog({
            title: title, modal: true, height: 'auto', width: width,
            buttons: buttons
        });
        return dia;
    },
    showDialog: function(template, title, state, w, h) {
        var html = CSC.getFile(CSC.getContextPath()+template+".html");
        var dia = "<div class='ModDialog'>"+html+"</div>";
        dia = jQueryEnterprise(dia);
        
        var js =  CSC.getFile(CSC.getContextPath()+template+".js");
        var handlers = eval(js);

        var b = CSC.i18n(['button.ok', 'button.cancel']);
        var buttons = {};
        buttons[b['button.ok']]     = function() {
            if(handlers.onSubmit(jQueryEnterprise, dia, state))
                dia.dialog('close');
        };
        buttons[b['button.cancel']] = function() { dia.dialog('close'); };

        dia.dialog({
            title: title, modal: true, height: h, width: w,
            buttons: buttons
        });
        
        handlers.onShow(jQueryEnterprise, dia, state);
        
        return dia;
    },
    setProgress: function(dia, value, text) {
        var p = dia.find('#progress');
        p.text(text);
        p.css('background-size', value+"% 100%");
    },
    showProgress: function(title, value, text) {
        var dia = "<div class='ModDialog'><table style='width: 100%'><tbody><tr><td id='progress' class='SmModalProgress'></td></tr></tbody></table></div>";
        dia = jQueryEnterprise(dia);
        dia.dialog({ title: title, modal: true, height: "auto", width: "480px", resizable: false, dialogClass: "no-close" });
        
        CSC.setProgress(dia, value, text);
        
        return dia;
    },
    toI18N: function(dom) { // internationalizes all text with the class SmI18N
        var keys = [];
        dom.find('.SmI18N').each(function() { keys.push(jQueryEnterprise(this).text()); });
        var map = CSC.i18n(keys);
        dom.find('.SmI18N').each(function() {
            var node = jQueryEnterprise(this);
            var key = node.text();
            node.text(map[key]);
        });
    },
    dispatchEvent : function(ele , params){
    	if(typeof ele ==='string') ele = ele;
    	else if( null !== ele  && ele instanceof jQueryEnterprise) ele = ele[0];
    	var defaultParams = {'javax.faces.behavior.event': 'action', 'execute': '@all','render':'[]'};
    	if(params)
    		 jQueryEnterprise.extend(defaultParams,params);
    	jsf.ajax.request(ele, null,defaultParams );
    },
    _i18n: { },
    i18n: function(keys) {
    	
        var known = {};
        var unknown = [];
        for(var i = 0; i < keys.length; i++) {
            var k = keys[i];
            var v = CSC._i18n[k];
            if(v) known[k] = v;
            else  unknown.push(k);
        }
        if(unknown.length > 0) {
            var rpc = CSC.newRpcClient();
            var msg;
            try { msg = rpc.mod.getI18NMessages(unknown); } 
            catch(e) { return known; /* use defaults */ }
            
            msg = eval('('+msg+')');
            for(var i = 0; i < msg.length; i++) {
                var k = unknown[i];
                var m = msg[i];
                known[k] = CSC._i18n[k] = m;
            }
        }
        return known;
    },
    isIE : function(){
    	return navigator.userAgent.search("MSIE") >= 0;
    },    
    appletFilesToParse : function(data){ 
    	var rpc = CSC.newRpcClient();
    	return rpc.efsBean.getConvertedSerializePaths(data);    	
    }
};

function showCscWidget(div, state, template) {
    var body = CSC.getBody(div);
    var html = CSC.getFile(CSC.getContextPath()+template+".html");
    body.append(html);
    
    var js =  CSC.getFile(CSC.getContextPath()+template+".js");
    var handlers = eval(js);
    handlers.onShow(jQueryEnterprise, div, state);
}

function newCrossPlot(divID) {
    var div = CSC.getContainer(divID);
    var state = CSC.getState(div);
    showCscWidget(div, state, "/mod/dialog/newCrossPlot");
}

function newATV(divID) {
    var div = CSC.getContainer(divID);
    var state = CSC.getState(div);
    state.type = "atv";
    showCscWidget(div, state, "/mod/dialog/newGraph");
}

function newPMV(divID) {
    var div = CSC.getContainer(divID);
    var state = CSC.getState(div);
    state.type = "pmv";
    showCscWidget(div, state, "/mod/dialog/newGraph");
}

function tailMinusF(divID) {
    var div = CSC.getContainer(divID);
    var state = CSC.getState(div);
    showCscWidget(div, state, "/mod/dialog/tail-f");
}

function editGlobalQuery() {
    var title = CSC.i18n(['title.gq'])['title.gq'];
    CSC.showDialog("/gq/MatMaterial", title, {}, 500, 'auto');
}

function compareObjects(divID) {
    var div = CSC.getContainer(divID);
    var state = CSC.getState(div);
    showCscWidget(div, state, "/compare/"+state.compare);
}

function smCSAEWebstart(pid,key,url){
	var action="../../servlet/rest/jnlp?pid="+pid+"&key="+key+"&url="+url;
	var frm = document.getElementById("csaeForm");
	frm.action = action;
	frm.target = "_blank";
	frm.submit();
}

function createBFS(divID) {
    var div = CSC.getContainer(divID);
    var state = CSC.getState(div);
    div.bfs(state);
}

var APP = {
     busyTimeout: 2000,
     busyTimer: false,
     smBrowserScroll:{top : 0, left : 0},
     
     /**
      * returns Dialog object which containes objects such as dilaog container,scrollpane,shadow, richfaces popup object
      */
     getDialogData : function(id){
    	 var ele = document.getElementById(id);
    	 var dlg = jQueryEnterprise(ele);
    	 var dlgContainer = dlg.find("DIV.rf-pp-cntr");
    	 var dlgScrollPane = dlg.find("DIV.rf-pp-cnt-scrlr");
    	 var dlgShadow = dlg.find("DIV.rf-pp-shdw");
    	 var d  = dlg.attr("id");
    	 var popup = RichFaces.$(d);
    	 return {popup : popup , scrollPane : dlgScrollPane , shadow : dlgShadow , container : dlgContainer};
     },
     
     /**
      * Auto size(resize) the dialog based on contents 
      */
     resizeDialog : function(id){
    	 var dialog = APP.getDialogData(id);
    	 var scrollPane = dialog.scrollPane;
    	 var popup = dialog.popup;
    	 var scrollData = scrollPane.hasScrollBar();
    	 if(scrollData.width > 0 || scrollData.height  >0){
    		 popup.resize(10,10);
    		 var dlgShadow =dialog.shadow;
    		 var dlgContainer = dialog.container;
    		 var iframe = dlgContainer.find("iframe.rf-pp-ifr");
    		 var win = jQueryEnterprise(window);
    		 var h = win.height();
    		 var w = win.width();
    		 APP.addScrollToDialog(scrollPane,dlgContainer, dlgShadow,iframe, h , w);
    	 }
     },
     /**
      * Adds scroll bar to dialog if the scrollpane has more than given height or width
      */
     addScrollToDialog :  function(scrollPane,dlgContainer, dlgShadow,iframe, height , width){
    	 if(scrollPane.height() > height ){
    		 dlgContainer.css({"top":"10px","height" : (height-120) +"px"});
    		 scrollPane.css("height" , (height-120) +"px");
    		 dlgShadow.css("height" , (height-100) +"px");
    		 iframe.css("height" , (height-100) +"px");
    	 }
    	 if(scrollPane.width() > width ){
    		 dlgContainer.css({"left":"20px","width" : (width-70) +"px"});
    		 scrollPane.css("width" , (width-70) +"px");
    		 dlgShadow.css("width" , (width-70) +"px");
    		 iframe.css("width" , (width-70) +"px");
    	 }
     },
     
     resizeActiveClientDialog : function(){  
    	 jQueryEnterprise(".ui-dialog-content:visible").each(function () {
    		 var dlg = jQueryEnterprise( this );
    		 if(dlg.parent().hasClass('swsExtClientDialogResize')){
    			 var winH = jQueryEnterprise(window).height()
    			 var h = parseInt(0.8*winH);
    			 dlg.find('.SwsDiaExtension').css('max-height',(h+'px'));    			
    		 }
    		 dlg.dialog("option","position",dlg.dialog("option","position"));
    	    });    	
     },
     autoResizeDialog: function(){
    	 var height = jQueryEnterprise(window).height();
    		var width = jQueryEnterprise(window).width();
    		var content = jQueryEnterprise('.AutoResizeDialog');
    		var dialog = content.closest("div.ui-dialog");
    		dialog.css({
    			'min-height':height - 200+"px",
    			'width':width - 100 + "px",
    			'top':'20px',
    			'left':'30px'
    		});
    		content.css({
    			'min-height':height - 150+"px",
    			'overflow':'auto',
    			'height':height - 200+"px"
    		});
     },
     showBusy: function() {
         if(APP.busyTimer) clearTimeout(APP.busyTimer);
         APP.busyTime = false;
         
         var b = jQueryEnterprise('#smBusy');
         b.removeClass("BusyModal2");
         b.show().attr("waiting", "true");
         APP.busyTimer = setTimeout(function() { b.addClass("BusyModal2"); }, APP.busyTimeout);
     },
     hideBusy: function() {
         if(APP.busyTimer) clearTimeout(APP.busyTimer);
         APP.busyTime = false;
         jQueryEnterprise('#smBusy').hide().attr("waiting", "false");
     },
     /**
 	 * Returns closest selected row from the MOD
 	 */
 	 getClosestRow: function(num, ar) {
 		var i = 0, closest, closestDiff, currentDiff;
 		if (ar.length) {
 			closest = ar[0];
 			closestDiff = Math.abs(num - closest);
 			for (i; i < ar.length; i++) {
 				currentDiff = Math.abs(num - ar[i]);
 				if (currentDiff < closestDiff) {
 					closest = ar[i];
 					closestDiff = Math.abs(num - closest);
 				}
 			}
 			// returns first element that is closest to number
 			return closest;
 		}
 	}
};
function openUrl(url){
	window.open(url, "_blank");
}

/**  API to get Curve Html from given model and to plot the image */
function fetchCurveHtml(parentclientID , obj,widgetName ){
	var plot=jQueryEnterprise("img."+widgetName);
    obj=eval('('+obj+')');
    var model=JSON.stringify(obj['model']);
    var data = { model: model, format: "PNG"};
    var stamp = "car."+new Date().getTime().toString(36);
	CSC.rest("cache", data, function(text) {
    text = eval('('+text+')');
    var token = text.token;
    plot.attr('src', CSC.getContextPath()+"/servlet/rest/plot?cache="+token+"&rand="+stamp);
	});
}
